package org.kl.bf.utils;

import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springside.modules.mapper.JsonMapper;

import com.fasterxml.jackson.databind.JavaType;

/**
 * @Author hqm
 * @CreateTime 2014年8月5日 下午4:48:57
 */
public class KLServlets {

	private static JsonMapper jsonMapper = JsonMapper.nonEmptyMapper();// Json转换器

	/**
	 * 取得带相同前缀的Request Parameters, copy from spring WebUtils.
	 * filterRules:[{"field"
	 * :"configValue","op":"LIKE","value":"2014","javaType":
	 * "S"},{"field":"remark","op":"LIKE","value":"CSS"}] 返回的结果的Parameter名已去除前缀.
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
		Validate.notNull(request, "Request must not be null");
		Enumeration paramNames = request.getParameterNames();
		Map<String, Object> params = new TreeMap<String, Object>();
		if (prefix == null) {
			prefix = "";
		}
		while ((paramNames != null) && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String unprefixed = paramName.substring(prefix.length());
				String[] values = request.getParameterValues(paramName);
				if ((values == null) || (values.length == 0)) {
					// Do nothing, no values found at all.
				} else if (values.length > 1) {
					params.put(unprefixed, values);
				} else {
					params.put(unprefixed, values[0]);
				}
			}
		}
		String filterRules = request.getParameter("filterRules");
		if (StringUtils.isNotBlank(filterRules)) {
			buildFilterRules(params, filterRules);
		}
		return params;
	}

	private static void buildFilterRules(Map<String, Object> params, String filterRules) {
		JavaType beanListType = jsonMapper.contructCollectionType(List.class, FilterRules.class);
		List<FilterRules> beanList = jsonMapper.fromJson(filterRules, beanListType);
		for (FilterRules fr : beanList) {
			if (StringUtils.isBlank(fr.getField()) || StringUtils.isBlank(fr.getOp())) {
				continue;
			}
			// searchParams中key的格式为OPERATOR_FIELDNAME或者OPERATOR-JavaType_FIELDNAME
			if (StringUtils.isBlank(fr.getJavaType())) {// 如果没有javaType默认为String
				params.put(fr.getOp() + "_" + fr.getField(), fr.getValue());
			} else {
				params.put(fr.getOp() + "-" + fr.getJavaType() + "_" + fr.getField(), fr.getValue());
			}
		}
	}

}
